package net.obxlabs.tweetpad.stats;

import net.silentlycrashing.util.*;
import processing.core.*;

public class CharLine {
	
	// TODO sync this value with source line length/count somehow
	public static final int OFFSET_X = 264;
	public static final int FIRST_CHAR = 2;
	public static final int ANIM_DURATION = 60;
	
	private PApplet p;
	private int baseLineY;
	private int unitSize;
	private int numPoints;
	private int scalar;
	private int color;
	private int strokeWeight;
	private AnimatedPoint[] points;
	
	/** 
	 * Builds a CharLine with random stroke color and weight.
	 *  
	 * @param p the parent PApplet
	 * @param y the baseline value
	 * @param u the char unit size
	 */
	public CharLine(PApplet p, int y, int u) {
		this(p, y, u, p.color(MiscMath.randRange(100, 150)), MiscMath.randRange(1, 5));
	}
	
	/**
	 * Builds a CharLine.
	 * 
	 * @param p the parent PApplet
	 * @param y the baseline value
	 * @param u the char unit size
	 * @param color the line color
	 * @param weight the stroke weight
	 */
	public CharLine(PApplet p, int y, int u, int color, int weight) {
		this.p = p;
		
		// calculate the dimensions
		numPoints = (140/Counter.CHARS_PER_SLICE)+7;  // 7 extra points for padding on the curve
		scalar = (p.width-OFFSET_X)/(numPoints-2);
		
		// set the line properties
		baseLineY = y;
		unitSize = u;
		this.color = color;
		strokeWeight = weight;

		points = new AnimatedPoint[numPoints];
		
		// init the points
		for (int i=0; i < numPoints-2; i++) {
			points[i] = new AnimatedPoint(scalar*(i-1), baseLineY);
		}
		points[numPoints-2] = new AnimatedPoint(p.width, baseLineY);
		points[numPoints-1] = new AnimatedPoint(p.width+scalar, baseLineY);
		
		p.registerPre(this);
	}
	
	public synchronized void pre() {
    	for (int i=0; i < numPoints; i++) {
    		points[i].pre();
    	}
    }
	
	public void addCharCount(int n) {
		points[FIRST_CHAR+n].moveTo(points[FIRST_CHAR+n].x, points[FIRST_CHAR+n].y+unitSize, ANIM_DURATION);
	}
	
	public void subCharCount(int n) {
		points[FIRST_CHAR+n].moveTo(points[FIRST_CHAR+n].x, points[FIRST_CHAR+n].y-unitSize, ANIM_DURATION);
	}
	
	/**
	 * Draws the StatLine.
	 */
	public void draw() {
		p.fill(color, 100);
		p.stroke(color);
		p.strokeWeight(strokeWeight);
		p.beginShape();
		for (int i=0; i < numPoints-2; i++) {
			p.curveVertex(points[i].x, points[i].y);
		}
		p.vertex(points[numPoints-2].x, points[numPoints-2].y);
		p.vertex(points[numPoints-1].x, points[numPoints-1].y);
		//p.vertex(points[0].x, points[0].y);
		p.endShape();
	}
	
	public void reset() {
		for (int i=0; i < numPoints; i++) {
			points[i].moveTo(points[i].x, baseLineY, ANIM_DURATION);
		}
	}
}
